import { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import api from '../api/axiosConfig';
import useAuthStore from '../store/authStore';
import axios from 'axios'; // 【FIX】Import the axios library here.

interface Team {
  _id: string;
  name: string;
}

const UploadWorkPage = () => {
  const [title, setTitle] = useState('');
  const [description, setDescription] = useState('');
  const [teamId, setTeamId] = useState('');
  const [userTeams, setUserTeams] = useState<Team[]>([]);
  
  const [error, setError] = useState('');
  const [success, setSuccess] = useState('');
  const navigate = useNavigate();
  const { userInfo } = useAuthStore();

  useEffect(() => {
    const fetchUserTeams = async () => {
      if (userInfo) {
        try {
          const { data } = await api.get(`/users/profile`);
          setUserTeams(data.teams || []);
          if (data.teams && data.teams.length > 0) {
            setTeamId(data.teams[0]._id);
          }
        } catch (err) {
          setError('无法加载队伍信息列表TAT');
        }
      }
    };
    fetchUserTeams();
  }, [userInfo]);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError('');
    setSuccess('');

    if (!title || !description || !teamId) {
      setError('需要填写所有字段哦');
      return;
    }

    try {
      await api.post('/works', {
        title,
        description,
        teamId,
        thumbnailUrl: `https://via.placeholder.com/400x300.png?text=${title.replace(' ', '+')}`
      });

      setSuccess('作品提交成功! 等待管理员审核...');
      setTimeout(() => {
        navigate('/works');
      }, 2000);

    } catch (err) {
      if (axios.isAxiosError(err)) {
        setError(err.response?.data?.message || '提交失败TAT');
      } else {
        setError('未知错误TAT');
      }
    }
  };

  return (
    <div style={{ maxWidth: '600px', margin: '0 auto' }}>
      <h2>上传你的作品!</h2>
      <form onSubmit={handleSubmit}>
        <div style={{ marginBottom: '1rem' }}>
          <label>作品名:</label>
          <input type="text" value={title} onChange={(e) => setTitle(e.target.value)} required style={{ width: '100%', padding: '8px' }} />
        </div>
        <div style={{ marginBottom: '1rem' }}>
          <label>作品描述:</label>
          <textarea value={description} onChange={(e) => setDescription(e.target.value)} required style={{ width: '100%', padding: '8px', minHeight: '120px' }} />
        </div>
        <div style={{ marginBottom: '1rem' }}>
          <label>队伍名:</label>
          <select value={teamId} onChange={(e) => setTeamId(e.target.value)} required style={{ width: '100%', padding: '8px' }}>
            {userTeams.length > 0 ? (
              userTeams.map(team => (
                <option key={team._id} value={team._id}>{team.name}</option>
              ))
            ) : (
              <option disabled value="">你需要先加入或者创建一个队伍哦</option>
            )}
          </select>
        </div>

        {error && <p style={{ color: 'red' }}>{error}</p>}
        {success && <p style={{ color: 'green' }}>{success}</p>}
        
        <button type="submit">提交</button>
      </form>
    </div>
  );
};

export default UploadWorkPage;